package com.bawei.home.dialog

import android.content.DialogInterface
import android.graphics.Color
import android.graphics.drawable.ColorDrawable
import android.os.Bundle
import android.view.KeyEvent
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.view.Window
import android.view.WindowManager
import androidx.fragment.app.DialogFragment
import androidx.fragment.app.FragmentManager
import androidx.fragment.app.activityViewModels
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.lifecycleScope
import androidx.lifecycle.repeatOnLifecycle
import androidx.recyclerview.widget.LinearLayoutManager
import com.bawei.common.entity.CommendEntity
import com.bawei.home.HomeUiState
import com.bawei.home.HomeViewIntent
import com.bawei.home.adapter.ViewCommendAdapter
import com.bawei.home.databinding.VideoCommendListBinding
import com.bawei.home.viewmodel.HomeViewModel
import com.blankj.utilcode.util.ToastUtils
import kotlinx.coroutines.launch

/**
 * 视频评论列表
 */
class VideoCommendFragment(private val itemId: String): DialogFragment(), DialogInterface.OnKeyListener {

    private lateinit var mDataBinding: VideoCommendListBinding
    private val mViewModel: HomeViewModel by activityViewModels()

    private lateinit var mAdapter: ViewCommendAdapter
    private var commendList = mutableListOf<CommendEntity>()

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
        //取消Title
        dialog?.requestWindowFeature(Window.FEATURE_NO_TITLE)
        //获取DataBinding
        mDataBinding = VideoCommendListBinding.inflate(inflater, container, false)
        //初始化组件
        initView()
        //初始化数据
        initData()
        //更新UI
        updateUi()
        return mDataBinding.root
    }

    override fun onStart() {
        super.onStart()
        dialog?.window?.setLayout(WindowManager.LayoutParams.MATCH_PARENT, WindowManager.LayoutParams.MATCH_PARENT) // 设置窗口大小
        dialog?.window?.attributes?.dimAmount = 0.2f //设置背景透明度
        dialog?.window?.setBackgroundDrawable(ColorDrawable(Color.TRANSPARENT)) //设置背景色
        //设置取消
        dialog?.setCancelable(true)
        //设置OnKey事件
        dialog?.setOnKeyListener(this)
    }

    override fun onKey(dialog: DialogInterface?, keyCode: Int, event: KeyEvent?): Boolean {
        if(keyCode == KeyEvent.KEYCODE_BACK){
            dismiss()
            return true
        }
        return false
    }

    override fun show(manager: FragmentManager, tag: String?) {
       if(isAdded || isVisible) return
       var ft = manager.beginTransaction()
       ft.remove(this)
       ft.add(this, tag)
       ft.commitAllowingStateLoss()
    }

    override fun dismiss() {
       dismissAllowingStateLoss()
    }

    private fun initData() {
        lifecycleScope.launch {
            mViewModel.channel.send(HomeViewIntent.LoadVideoCommends(0, itemId))
        }
    }

    private fun updateUi() {
       lifecycleScope.launch {
           lifecycle.repeatOnLifecycle(Lifecycle.State.RESUMED){
               collectUiState()
           }
       }
    }

    private fun initView() {
        mDataBinding.ctlRoot.setOnClickListener {
            this@VideoCommendFragment.dismiss()
        }

        //取消按钮事件
        mDataBinding.ivCancel.setOnClickListener {
            this@VideoCommendFragment.dismiss()
        }
        //发送评论按钮点击事件
        mDataBinding.tvSend.setOnClickListener {
            ToastUtils.showLong("发布评论")
        }

        //初始化RecyclerView
        mDataBinding.rvComment.layoutManager = LinearLayoutManager(requireContext(),  LinearLayoutManager.VERTICAL, false)
        mAdapter = ViewCommendAdapter(commendList)
        mDataBinding.rvComment.adapter = mAdapter
    }

    private suspend fun collectUiState(){
        mViewModel.uiState.collect{
            when(it){
                is HomeUiState.LoadVideoCommendSuccess -> {
                    if(it.list.isNotEmpty()){
                       commendList.clear()
                    }
                    commendList.addAll(it.list)
                    mAdapter.notifyDataSetChanged()

                }
                is HomeUiState.LoadVideoCommendFail -> {
                    ToastUtils.showLong(it.msg)
                }
                else -> {}
            }
        }
    }

}